package com.uxsino.watcher.lib.interceptor;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.uxsino.commons.lic.AppProperty;
import com.uxsino.commons.model.JsonModel;
import com.uxsino.watcher.lib.annoation.Business;
import com.uxsino.watcher.lib.services.LicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LicInterceptor extends HandlerInterceptorAdapter {
    private final Logger LOG = LoggerFactory.getLogger(LicInterceptor.class);

    @Autowired
    LicService licService;

    public static final String[] EXCLUDE_PATTERN = {
            "/info",
            "/state"
    };


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            Method method = ((HandlerMethod) handler).getMethod();
            Object cls = ((HandlerMethod) handler).getBean();
            Business busMethod = null;
            Business busCls  =null;

            String bus = null;
            Boolean validate = null;
            if(method != null){
                busMethod = method.getAnnotation(Business.class);
            }
            if(cls != null){
                busCls = cls.getClass().getAnnotation(Business.class);
            }
            //确定业务
            if(busMethod != null){
                bus = busMethod.name();
                validate = busMethod.validate();
            }
            if(Strings.isNullOrEmpty(bus)){
                if(busCls != null ){
                    bus = busCls.name();
                }
            }
            //确定是否根据证书匹配限制
            if(validate == null){
                if(busCls != null ){
                    validate = busCls.validate();
                }
            }
            JsonModel illegal = new JsonModel(false, "模块["+bus+"]未注册，请联系系统供应商。");
            illegal.setCode(-1);
            if(validate != null && validate){//需要进行校验
                AppProperty property = licService.get();
                if(!Strings.isNullOrEmpty(bus)){
                    if(property == null || !property.permission(bus)){
                        response.setContentType("application/json;charset=UTF-8");
                        response.setCharacterEncoding("UTF-8");
                        response.getWriter().write(JSON.toJSONString(illegal));
                        return false;
                    }
                }else{
                    LOG.warn("[license-module-controller] 业务名称未配置:  {}.{}", (cls!=null?cls.getClass().getSimpleName():""), (method != null? method.getName(): ""));
                }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
